package com.yanfan.zutai.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.yanfan.common.utils.DateUtils;
import com.yanfan.zutai.domain.BDevicePhone;
import com.yanfan.zutai.domain.BDeviceWarn;
import com.yanfan.zutai.domain.BShortMessage;
import com.yanfan.zutai.domain.vo.BDeviceMessage;
import com.yanfan.zutai.mapper.BDevicePhoneMapper;
import com.yanfan.zutai.service.IBDevicePhoneService;
import com.yanfan.zutai.service.IBShortMessageService;
import com.yanfan.zutai.util.DateUtilLocal;
import com.yanfan.zutai.util.Detect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 短信报警电话Service业务层处理
 *
 * @author ruoyi
 * @date 2021-09-15
 */
@Service
public class BDevicePhoneServiceImpl implements IBDevicePhoneService {
    @Value("${ruoyi.accessKeyId}")
    private static String accessKeyId;
    @Value("${ruoyi.accessKeySecret}")
    private static String accessKeySecret;
    @Value("${ruoyi.signName}")
    private static String signName;
    @Value("${ruoyi.templateCode}")
    private static String templateCode;
    @Autowired
    private BDevicePhoneMapper bDevicePhoneMapper;
    @Autowired
    private IBShortMessageService bShortMessageService;

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    private static Boolean sendShortMessage(String message, String phone) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(message);
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        boolean isSuccess = false;
        if ("OK".equals(sendSmsResponse.getBody().getMessage())) {
            System.out.println("短信发送成功");
            isSuccess = true;
            return isSuccess;
        } else {
            System.out.println("短信发送失败，说明：" + JSON.toJSONString(sendSmsResponse.getBody()));
            return isSuccess;
        }

    }

    // 计算短信字数
    private static Integer getShortCount(BDeviceMessage message) {
        String str = "您好，" + message.getDeviceName() + "于" + message.getTime() + "发出" + message.getWarnType() + "，请您及时前往" + message.getWarnPlace() + "进行处理。";
        if (str.length() % 60 == 0) {
            return str.length() / 60;
        } else {
            return str.length() / 60 + 1;
        }
    }

    public static void main(String[] args) throws Exception {
        BDeviceMessage bDeviceMessage = new BDeviceMessage();
        bDeviceMessage.setWarnPlace("江苏徐州");
        bDeviceMessage.setDeviceName("测试设备");
        bDeviceMessage.setTime(DateUtil.format(new Date(), "HH:mm"));
        bDeviceMessage.setWarnType("高温报警");
        String message = JSON.toJSONString(bDeviceMessage);
        System.out.println(message);
        // sendShortMessage(message,"13338970355");
        System.out.println(getShortCount(bDeviceMessage));
    }

    /**
     * 查询短信报警电话
     *
     * @param id 短信报警电话ID
     * @return 短信报警电话
     */
    @Override
    public BDevicePhone selectBDevicePhoneById(Long id) {
        return bDevicePhoneMapper.selectBDevicePhoneById(id);
    }

    /**
     * 查询短信报警电话列表
     *
     * @param bDevicePhone 短信报警电话
     * @return 短信报警电话
     */
    @Override
    public List<BDevicePhone> selectBDevicePhoneList(BDevicePhone bDevicePhone) {
        return bDevicePhoneMapper.selectBDevicePhoneList(bDevicePhone);
    }

    /**
     * 新增短信报警电话
     *
     * @param bDevicePhone 短信报警电话
     * @return 结果
     */
    @Override
    public int insertBDevicePhone(BDevicePhone bDevicePhone) {
        bDevicePhone.setCreateTime(DateUtils.getNowDate());
        Snowflake snowflake = IdUtil.getSnowflake(6, 2);
        long id = snowflake.nextId();
        bDevicePhone.setId(id);
        return bDevicePhoneMapper.insertBDevicePhone(bDevicePhone);
    }

    /**
     * 修改短信报警电话
     *
     * @param bDevicePhone 短信报警电话
     * @return 结果
     */
    @Override
    public int updateBDevicePhone(BDevicePhone bDevicePhone) {
        bDevicePhone.setUpdateTime(DateUtils.getNowDate());
        return bDevicePhoneMapper.updateBDevicePhone(bDevicePhone);
    }

    /**
     * 批量删除短信报警电话
     *
     * @param ids 需要删除的短信报警电话ID
     * @return 结果
     */
    @Override
    public int deleteBDevicePhoneByIds(Long[] ids) {
        return bDevicePhoneMapper.deleteBDevicePhoneByIds(ids);
    }

    /**
     * 删除短信报警电话信息
     *
     * @param id 短信报警电话ID
     * @return 结果
     */
    @Override
    public int deleteBDevicePhoneById(Long id) {
        return bDevicePhoneMapper.deleteBDevicePhoneById(id);
    }

    @Override
    public Integer sendMessage(BDeviceWarn bDeviceWarn, BShortMessage bShortMessage) throws Exception {
        BDevicePhone bDevicePhone = new BDevicePhone();
        bDevicePhone.setDeviceMac(bDeviceWarn.getDeviceMac());
        List<BDevicePhone> bDevicePhones = bDevicePhoneMapper.selectBDevicePhoneList(bDevicePhone);
        Boolean isToday = false;
        Integer sendSuccess = 0;// 短信发送数量
        for (int i = 0; i < bDevicePhones.size(); i++) {
            bDevicePhone = bDevicePhones.get(i);
            isToday = DateUtilLocal.isToday(bDevicePhone.getWarnTime());
            if (bDevicePhone.getWarnNum() == null) {
                bDevicePhone.setWarnNum(0);
            }
            if (isToday && bDevicePhone.getWarnNum() <= bDevicePhone.getWarnRate()) {
                bDevicePhone.setWarnNum(bDevicePhone.getWarnNum() + 1);
                // 阿里云发送短信
                BDeviceMessage bDeviceMessage = new BDeviceMessage();
                if (Detect.notEmpty(bDeviceWarn.getAddress())) {
                    bDeviceMessage.setWarnPlace(bDeviceWarn.getAddress());
                } else {
                    bDeviceMessage.setWarnPlace("--");
                }
                bDeviceMessage.setWarnType(bDeviceWarn.getWarnMessage());
                bDeviceMessage.setTime(DateUtil.format(bDeviceWarn.getWarnTime(), "HH:mm:ss"));
                bDeviceMessage.setDeviceName(bDeviceWarn.getDeviceName());
                String message = JSON.toJSONString(bDeviceMessage);
                Boolean isSuccess = false;
                if (Detect.notEmpty(bDevicePhone.getWarnPhone())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone1())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone1());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone2())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone2());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone3())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone3());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone4())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone4());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (isSuccess) {
                    bDevicePhoneMapper.updateBDevicePhone(bDevicePhone);
                }
            } else if (!isToday) {
                // 阿里云发送短信
                BDeviceMessage bDeviceMessage = new BDeviceMessage();
                if (Detect.notEmpty(bDeviceWarn.getAddress())) {
                    bDeviceMessage.setWarnPlace(bDeviceWarn.getAddress());
                } else {
                    bDeviceMessage.setWarnPlace("--");
                }
                bDeviceMessage.setWarnType(bDeviceWarn.getWarnMessage());
                bDeviceMessage.setTime(DateUtil.format(bDeviceWarn.getWarnTime(), "HH:mm:ss"));
                bDeviceMessage.setDeviceName(bDeviceWarn.getDeviceName());
                String message = JSON.toJSONString(bDeviceMessage);
                Boolean isSuccess = false;
                if (Detect.notEmpty(bDevicePhone.getWarnPhone())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone1())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone1());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone2())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone2());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone3())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone3());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                if (Detect.notEmpty(bDevicePhone.getWarnPhone4())) {
                    boolean isSendSuccess = sendShortMessage(message, bDevicePhone.getWarnPhone4());
                    if (isSendSuccess) {
                        isSuccess = true;
                        Integer shortCount = getShortCount(bDeviceMessage);
                        sendSuccess = sendSuccess + shortCount;
                    }
                }
                bDevicePhone.setWarnTime(new Date());
                bDevicePhone.setWarnNum(1);
                if (isSuccess) {
                    bDevicePhoneMapper.updateBDevicePhone(bDevicePhone);
                }
            }
        }
        bShortMessage.setShortUseCount(bShortMessage.getShortUseCount() + sendSuccess);
        bShortMessage.setShortNotUseCount(bShortMessage.getShortNotUseCount() - sendSuccess);
        bShortMessageService.updateBShortMessage(bShortMessage);
        return 0;
    }
}
